<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="公司状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="companyId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :header-cell-style="{'background': '#F6F8FB'}"
      :height="maxHeight"
      stripe
      v-scrollbar="'.el-table__body-wrapper'"
    >
      <el-table-column prop="companyName" label="公司名称"></el-table-column>
      <el-table-column label="类型" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.companyOrDept == 2">部门</el-tag>
          <el-tag v-if="scope.row.companyOrDept == 1">公司</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <template v-for="dict in statusOptions">
            <el-tag v-if="dict.dictValue == scope.row.status">{{dict.dictLabel}}</el-tag>
          </template>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <div class="operate-group">
            <span
              style="cursor:pointer;color: #409eff;font-size:12px;"
              type="text"
              class="el-icon-edit"
              :plain=false
              @click="handleUpdate(scope.row)"
            >修改</span>
            <span
              style="cursor:pointer;color: #409eff;font-size:12px;"
              type="text"
              class="el-icon-plus"
              :plain=false
              @click="handleAdd(scope.row)"
            >新增</span>
            <span
              style="cursor:pointer;color: #409eff;font-size:12px;"
              type="text"
              class="el-icon-delete"
              :plain=false
              @click="handleDelete(scope.row)"
            >删除</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改公司对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body v-if="open">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" @submit.native.prevent>
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0 && isedit == 0">
            <el-form-item label="上级公司" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级公司" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="isedit == 0">
            <el-form-item label="类型" v-if="companyOrDept == '1' && isshow==1">
              <el-radio-group v-model="form.companyOrDept">
                <el-radio label="1">公司</el-radio>
                <el-radio label="2">部门</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="companyOrDept == '1' && form.companyOrDept== '1'" label="公司名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="companyOrDept == '1' && form.companyOrDept== '1'" label="法人" prop="charge">
              <el-input v-model="form.charge" placeholder="请输入法人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="companyOrDept == '2' || form.companyOrDept== '2'" label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="companyOrDept == '2' || form.companyOrDept== '2'" label="负责人" prop="charge">
              <el-input v-model="form.charge" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept,delCompany, addDept, updateDept, listDeptExcludeChild,treeselect } from "@/api/system/company";
import RightToolbar from "@/components/RightToolbar"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {delData} from "@/api/dynamic/dynamic";

export default {
  inject: ['app'],
  name: "Dept",
  components: { Treeselect,RightToolbar },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 公司树选项
      deptOptions: [],
      companyData:[],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions2: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 查询参数
      queryParams: {
        companyName: undefined,
        status: undefined
      },
      statusOptions:null,
      // 表单参数
      form: {},
      isshow:1,
      isedit:0,
      companyOrDept:"1",
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级公司不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        tel: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  watch: {
    // 监听deptId
    'form.parentId': 'currDeptChange'
  },
  computed: {
    maxHeight(){
      return this.app.screenHeight - 270
    },
  },
  methods: {
    currDeptChange(val) {
      var show=this.isshow;
      var companyOrDept='1';
      this.companyData.forEach(function (item) {
        if (item.companyOrDept === '1' && item.companyId == val) {
          companyOrDept=item.companyOrDept;
          show=1;
        }else if(item.companyOrDept === '2' && item.companyId == val){
          companyOrDept=item.companyOrDept;
          show=0;
        }
      });
      this.isshow=show;
      this.companyOrDept=companyOrDept;
    },
    /** 查询公司列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.companyData=response.data;
        this.deptList = this.handleTree(response.data, "companyId", 'parentId');
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions2 = response.data;
      });
    },
    /** 转换公司数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.companyId,
        label: node.companyName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        companyId: undefined,
        parentId: undefined,
        companyName: undefined,
        deptName: undefined,
        orderNum: 1,
        charge: undefined,
        tel: undefined,
        email: undefined,
        status: "0",
        companyOrDept:"1"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.isedit=0;
      if(row.companyOrDept==2){
        this.companyOrDept='2';
        this.isshow=0;
      }else{
        this.companyOrDept='1';
        this.isshow=1;
      }
      this.reset();
      listDept().then(response => {
        this.companyData=response.data;
        this.deptOptions = this.handleTree(response.data, "companyId",'parentId');
      });
      if (row != undefined) {
        this.form.parentId = row.companyId;
        this.form.companyOrDept = row.companyOrDept;
      }
      this.open = true;
      this.title = "添加公司";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.companyId).then(response => {
        this.form = response.data;
        if(this.form.companyOrDept==='1'){
          this.form.companyOrDept='1';
          this.isshow=1;
          this.title = "修改公司";
        }else{
          this.form.companyOrDept='2';
          this.isshow=0;
          this.title = "修改部门";
        }
        this.isedit = 1;
        this.open = true;
      });
      listDeptExcludeChild(row.companyId).then(response => {
        this.deptOptions = this.handleTree(response.data, "companyId",'parentId');
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.companyId != undefined) {
            updateDept(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.companyName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        if(row.companyOrDept=='1'){
          return delCompany(row.companyId);
        }else{
          return delDept(row.companyId);
        }
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    }
  }
};
</script>
